package com.itheima.tanhua.server.interceptor;

import com.itheima.commons.holder.TokenHolderUserId;
import com.itheima.commons.holder.TokenHolderPhone;
import com.itheima.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


/**
 * @author H Monster
 */
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //获取请求头信息
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            throw new Exception("token不能为空");
        }

        //解析token
        Claims claims = JwtUtils.getClaims(authorization);
        Integer userId = (Integer) claims.get("userId");

        String phone = (String) claims.get("phone");

        if (Objects.isNull(userId)) {
            throw new Exception("token已失效");

        }

        //将解析后的userId, 给controller, 或者service
        TokenHolderUserId.set(userId.toString());

        TokenHolderPhone.set(phone);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        // 该步骤保证ThreadLocal内存不一直增长,导致溢出
        TokenHolderUserId.remove();
        TokenHolderPhone.remove();
    }
}
